package com.lindroy.androidplayer.ui.main.fragment

import android.os.Bundle
import android.view.View
import androidx.fragment.app.viewModels
import com.lindroy.androidplayer.R
import com.lindroy.androidplayer.base.BaseLazyFragment
import com.lindroy.androidplayer.databinding.FragmentProjectBinding
import com.lindroy.androidplayer.logic.network.base.http.observeResponse
import com.lindroy.androidplayer.ui.adapter.ProjectTabAdapter
import com.lindroy.androidplayer.utils.contactToViewPager
import com.lindroy.androidplayer.utils.toHtml
import com.lindroy.androidplayer.viewmodels.ProjectTypeViewModel

/**
 * @author Lin
 * @date 2022/1/10
 * @function 项目
 * @Description
 */
class ProjectFragment : BaseLazyFragment<FragmentProjectBinding>() {

    private lateinit var adapter: ProjectTabAdapter

    private val projectViewModel by viewModels<ProjectTypeViewModel>()

    override fun FragmentProjectBinding.initView(savedInstanceState: Bundle?) {
        vm = projectViewModel
        initToolbar(R.string.project, false)
        adapter = ProjectTabAdapter(this@ProjectFragment)
        vpProject.adapter = adapter
    }

    override fun FragmentProjectBinding.initListener() {
        projectViewModel.projectTypesLiveData.data.observeResponse(viewLifecycleOwner) { types ->
            vpProject.offscreenPageLimit = types.size
            adapter.setData(types.map { it.id })
            tab.tabLayout.contactToViewPager(vpProject, types.map { it.name.toHtml() })
        }
    }

    override fun lazyLoad() {
        projectViewModel.projectTypesLiveData.load()
    }

    override fun onRetryClick(view: View) {
        projectViewModel.projectTypesLiveData.retry()
    }

    companion object{
        fun newInstance() = ProjectFragment()
    }

}